package com.sc.study.exam.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.sc.common.annotation.Excel;
import com.sc.study.exam.domain.ScQuestion;
import com.sc.study.exam.domain.ScQuestionOption;
import com.sc.study.exam.domain.ScQuestionType;
import com.sc.study.foundation.domain.ScSubjectChapter;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sc.common.annotation.Log;
import com.sc.common.core.controller.BaseController;
import com.sc.common.core.domain.AjaxResult;
import com.sc.common.enums.BusinessType;
import com.sc.study.exam.domain.ScStudentTestexam;
import com.sc.study.exam.service.IScStudentTestexamService;
import com.sc.common.utils.poi.ExcelUtil;
import com.sc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生试卷Controller
 * 
 * @author sc
 * @date 2022-03-16
 */
@RestController
@RequestMapping("/study/studenttestexam")
public class ScStudentTestexamController extends BaseController
{
    @Autowired
    private IScStudentTestexamService scStudentTestexamService;

    /**
     * 查询学生试卷列表
     */
    @PreAuthorize("@ss.hasPermi('study:studenttestexam:list')")
    @GetMapping("/list")
    public TableDataInfo list(ScStudentTestexam scStudentTestexam)
    {
        startPage();
        List<ScStudentTestexam> list = scStudentTestexamService.selectScStudentTestexamByStudentAndTextExam(scStudentTestexam);
        return getDataTable(list);
    }

    /**
     * 线下考试： 导出添加学生成绩 excel 模板
     *
     * @param response
     */
    @Log(title = "线下考试导入学生成绩模板", businessType = BusinessType.EXPORT)
    @PostMapping("/export/excel/model")
    public ResponseEntity<byte[]> exportExcelModel(HttpServletResponse response) throws IOException {
        //创建一个excel
        Workbook workbook = new XSSFWorkbook();
        //创建sheet页
        Sheet sheet = workbook.createSheet();

        Row row = sheet.createRow(0);

        Cell studentIdCell = row.createCell(0);
        studentIdCell.setCellValue("学生编号");

        Cell scoreCell = row.createCell(1);
        scoreCell.setCellValue("分数");

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        workbook.write(bos);

        HttpHeaders headers = new HttpHeaders();
        //响应头的的流名称
        headers.setContentDispositionFormData(
                "attachment",
                new String(("导入学生数据模板.xlsx").getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
        //响应头出数据的格式为STREAM（流）
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bos.toByteArray(), headers, HttpStatus.OK);

        return responseEntity;

    }


    /**
     * 线下考试： 导入学生成绩
     */
    @Log(title = "题目模板", businessType = BusinessType.IMPORT)
    @PostMapping("/import/excel")
    public AjaxResult importExcelModel(Long importTestExamId, MultipartFile file) throws Exception {

        //将传入进来的文件转化为工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        //获取excel sheet页面
        Sheet sheet = workbook.getSheetAt(0);
        //获取当前sheet页行数
        int rows = sheet.getPhysicalNumberOfRows();

        List<ScStudentTestexam> studentTestExamList = new ArrayList<>();
        for (int i = 1; i < rows; i++) {
            Row row = sheet.getRow(i);

            ScStudentTestexam scStudentTestexam = new ScStudentTestexam();

            scStudentTestexam.setTestexamid(importTestExamId);
            scStudentTestexam.setStudentid(Long.valueOf((int)row.getCell(0).getNumericCellValue()));
            scStudentTestexam.setScore(Long.valueOf((int)row.getCell(1).getNumericCellValue()));

            //判断是否存在
            scStudentTestexam.setId(scStudentTestexamService.getIdByStudentAndTextExam(scStudentTestexam.getStudentid(), scStudentTestexam.getTestexamid()));

            studentTestExamList.add(scStudentTestexam);
        }


        return AjaxResult.success(scStudentTestexamService.excelImportBatchAdd(importTestExamId, studentTestExamList));
    }




    /**
     * 导出学生试卷列表
     */
    @PreAuthorize("@ss.hasPermi('study:studenttestexam:export')")
    @Log(title = "学生试卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ScStudentTestexam scStudentTestexam)
    {
        List<ScStudentTestexam> list = scStudentTestexamService.selectScStudentTestexamList(scStudentTestexam);
        ExcelUtil<ScStudentTestexam> util = new ExcelUtil<ScStudentTestexam>(ScStudentTestexam.class);
        util.exportExcel(response, list, "学生试卷数据");
    }

    /**
     * 获取学生试卷详细信息
     */
    @PreAuthorize("@ss.hasPermi('study:studenttestexam:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(scStudentTestexamService.selectScStudentTestexamById(id));
    }

    /**
     * 新增学生试卷
     */
    @PreAuthorize("@ss.hasPermi('study:studenttestexam:add')")
    @Log(title = "学生试卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ScStudentTestexam scStudentTestexam) {
        return toAjax(scStudentTestexamService.insertScStudentTestexam(scStudentTestexam));
    }

    /**
     * 批量添加
     * @param scStudentTestExamList
     * @return
     */
    @PostMapping("/batchAdd")
    public AjaxResult batchAdd(@RequestBody List<ScStudentTestexam> scStudentTestExamList)
    {
        return toAjax(scStudentTestexamService.batchAdd(scStudentTestExamList));
    }

    /**
     * 修改学生试卷
     */
    @PreAuthorize("@ss.hasPermi('study:studenttestexam:edit')")
    @Log(title = "学生试卷", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ScStudentTestexam scStudentTestexam)
    {
        return toAjax(scStudentTestexamService.updateScStudentTestexam(scStudentTestexam));
    }

    /**
     * 根据考试编号和学生进行删除
     * @param testExamId 考试编号
     * @param studentIds 学生编号集合
     * @return
     */
    @DeleteMapping("/{testExamId}/{studentIds}")
    public AjaxResult removeByTestExamIdAndStudentId(@PathVariable("testExamId") Integer testExamId,@PathVariable("studentIds") Integer[] studentIds)
    {
        return toAjax(scStudentTestexamService.removeByTestExamIdAndStudentId(testExamId, studentIds));
    }


    /**
     * 删除学生试卷
     */
    @PreAuthorize("@ss.hasPermi('study:studenttestexam:remove')")
    @Log(title = "学生试卷", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(scStudentTestexamService.deleteScStudentTestexamByIds(ids));
    }
}
